/**
 * Copyright 2011 Declan.z
 */
package com.mail163.email.location;

import java.io.Serializable;
import java.util.Date;

import org.json.JSONObject;

import com.mail163.email.Logs;
import com.mail163.email.util.Config;

/**
 * @author Declan.Z(declan.zhang@gmail.com)
 * @date 2011-12-16
 */
public class Location implements Serializable {

	public double radius;
	public double lat;
	public double lng;
	public String addr;
	public Date time; 
	public long locationTime; 
	private String sLat; 
	private String sLng;

	private Location() {
	}

	public Location(String lat, String lng) {
		sLat = lat;
		sLng = lng;
	}

	public static Location parseBaidu(String data) {
		Logs.v(Logs.LOG_TAG, "parseBaidu :" + data);
		Location location = null;
		try {
			JSONObject result = new JSONObject(data);
			if (result.getJSONObject("result").getInt("error") == 161) {
				location = new Location();
				JSONObject content = result.getJSONObject("content");
				JSONObject point = content.getJSONObject("point");
				location.lat = point.getDouble("y");// + Config.FIX_LAT ;
				location.lng = point.getDouble("x");// + Config.FIX_LNG ;
				location.sLat = location.lat + "";
				location.sLng = location.lng + "";
				JSONObject addr = content.getJSONObject("addr");
				location.addr = addr.getString("street"); // +
															// addr.getString("street_number");
				location.radius = content.getDouble("radius");
				location.time = new Date();
			}
		} catch (Exception e) {
			return null;
		}
		return location;
	}

	public static Location parseGears(String data) {
		Logs.v(Logs.LOG_TAG, "parseGears :" + data);
		Location location = null;
		try {
			location = new Location();
			JSONObject json = new JSONObject(data);
			JSONObject loc = json.getJSONObject("location");
			location.lat = loc.getDouble("latitude") + Config.FIX_LAT;
			location.lng = loc.getDouble("longitude") + Config.FIX_LNG;
			location.sLat = location.lat + "";
			location.sLng = location.lng + "";
			location.radius = loc.getDouble("accuracy");
			JSONObject addr = loc.getJSONObject("address");
			location.addr =
			// addr.getString("region") + addr.getString("city") +
			addr.getString("street")
			// + addr.getString("street_number")
			;
			location.time = new Date();
		} catch (Exception e) {
			return null;
		}
		return location;
	}

	public String getLng() {
		return sLng;
	}

	public String getLat() {
		return sLat;
	}

	public boolean isTooOld() {
		if (time == null) {
			return true;
		}
		long delta = new Date().getTime() - time.getTime();
		return delta > Config.LOCATION_RELOCATION_TIME;
	}

}
